package net.zjitc.dao.impl;

import net.zjitc.dao.UserDao;
import net.zjitc.domain.User;
import net.zjitc.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 2 * @Author: 洪瑶
 * 3 * @Date: 2018/10/8 18:41
 * 4
 */
public class UserDaoImpl implements UserDao {

    @Override
    public List<User> sqlfindAll() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user";
        List<User> list = (List<User>) queryRunner.query(sql,new BeanListHandler(User.class));
        return list;
    }

    @Override
    public void sqldelete(int id) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "delete from user where uid = ?";
        queryRunner.update(sql,id);
    }

    @Override
    public User sqllogin(String username, String password) throws SQLException {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username = ? and password = ?";
        User user = (User) runner.query(sql,new BeanHandler(User.class),new Object[]{username,password});
        return user;
    }

    @Override
    public Boolean sqlregister(User user)  {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username = ?";
        User users = null;
        try {
            users = (User) runner.query(sql,new BeanHandler(User.class),new Object[]{user.getUsername()});
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (users != null)
        {
            return false;
        }else {
            String sqls = "insert into user (username,password,email,phone,addr)values(?,?,?,?,?)";
            try {
                runner.update(sqls,new Object[]{user.getUsername(),user.getPassword(),user.getEmail(),user.getPhone(),user.getAddr()});
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return true;
        }
    }

    @Override
    public void active(String active) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "update user set state = ? ";

    }
}
